package server.proxy.factory;

import java.util.concurrent.Executor;

import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.http.HttpChunkAggregator;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;

import server.proxy.ProxyServerBlackListHandler;
import server.proxy.ProxyServerHandler;
import server.proxy.ProxyServerMailListHandler;
import server.proxy.ProxyServerPasswordHandler;
import server.proxy.ProxyServerRequestCounter;


/**
 * This class creates the pipes for client server connection
 * @author Maxim
 *
 */
public class ProxyServerPipelineFactory implements ChannelPipelineFactory{

	private Executor _threadPool;
	private String _proxyAddress;
	
	public ProxyServerPipelineFactory(Executor threadPool, String proxyAdress){
		
		this._threadPool = threadPool;
		this._proxyAddress = proxyAdress;
	}
	
	
	@Override
	public ChannelPipeline getPipeline() throws Exception {
		
		ChannelPipeline tChanelPipeLine = Channels.pipeline();
		
		tChanelPipeLine.addLast("decoder", new HttpRequestDecoder());
		
		//A ChannelHandler that aggregates an HttpMessage and its 
		//following HttpChunks into a single HttpMessage with no following HttpChunks.
		tChanelPipeLine.addLast("aggregator", new HttpChunkAggregator(Integer.MAX_VALUE));
		
		tChanelPipeLine.addLast("encoder", new HttpResponseEncoder());
		
		//password handler
		tChanelPipeLine.addLast("passwordHandler", new ProxyServerPasswordHandler(this._proxyAddress));
		
		//black list handler
		tChanelPipeLine.addLast("blackListHandler", new ProxyServerBlackListHandler());
		
		tChanelPipeLine.addLast("recievedMailListHandler", new ProxyServerMailListHandler());
		
		tChanelPipeLine.addLast("requestCounterHandler", new ProxyServerRequestCounter());
		
		//manage the connection to the remote host
		tChanelPipeLine.addLast("handler", new ProxyServerHandler(this._threadPool));
		
		return tChanelPipeLine;
	}
	
	

}
